package ed.hbut.supermarket1.service.impl;

import ed.hbut.supermarket1.dto.MerchandiseDto;
import ed.hbut.supermarket1.dto.SaleDto;
import ed.hbut.supermarket1.entity.Merchandise;
import ed.hbut.supermarket1.entity.Sale;
import ed.hbut.supermarket1.mapper.SaleMapper;
import ed.hbut.supermarket1.service.SaleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SaleServiceImpl implements SaleService {

    @Autowired
    public SaleMapper saleMapper;

    @Transactional
    @Override
    public void addSale(SaleDto saleDto) {

        Sale sale = new Sale();
        BeanUtils.copyProperties(saleDto, sale);

        //赋值日期
        log.info("拷贝的商品：{}", sale);
        sale.setSalesDate(LocalDateTime.now());

        //插入主表（订单表）
        log.info("插入主表 {}", sale);
        saleMapper.addSale(sale);
        saleDto.setSaleId(sale.getSalesID());
        log.info("主键id为:{}", saleDto.getSaleId());

        //插入merchandiseSale表
        log.info("插入关联表 {}", saleDto);
        saleMapper.addMerchandiseSales(saleDto);


    }


    /**
     * 实现查询订单逻辑
     *
     * @return
     */
    @Override
    public List<Sale> getAllSale() {


        return saleMapper.getAllSale();
    }

    @Override
    public List<MerchandiseDto> getMerchandiseBySaleId(int id) {

        return saleMapper.getMerchandiseBySaleId(id);
    }

    @Transactional
    @Override
    public void deleteSale(int id) {



        //删除关联表的记录
        saleMapper.deleteMerchandiseSale(id);
        //删除主表的记录
        saleMapper.deleteSale(id);

    }
}
